﻿var LastSelectDetailID = 0, CurrentRecord;
        function DocumentReady() {
            DirectMethod.DocumentReady({
                success: function() {
                    txtVoucherNo.focus();
                    if (hdDocumentID.getValue() == '')
                        AddTenRecord();
                },
                fulture: function(ex) {
                    alert(ex);
                }
            });
        }
        function AddTenRecord() {
           // for (var i = 0; i < 10; i++) {
                var newIndex = grDetail.addRecord({});
                var record = grDetail.store.getAt(newIndex);
                record.commit();
           // }
        }
        function SelectItem(combo, record, index) {

            var Record = grDetail.selModel.selections.items[0];
            if (record == undefined || record == null) {
                Record.set('ProductId', '');
                Record.set('ProductCode', '');
                Record.set('ProductName', '');
                Record.set('UnitId', '');
                Record.set('UnitPrice', '');
                Record.set('Quantity', '');
                Record.set('WarehouseId', '');
                Record.commit();
                return;
            }
            Record.set('ProductId', record.data.ProductId);
            Record.set('ProductCode', record.data.ProductCode);
            Record.set('ProductName', record.data.ProductName);
            Record.set('UnitId', record.data.InputUnit);
            Record.set('UnitName', record.data.InputUnitName);
            Record.set('UnitPrice', record.data.InputPrice);
            var QuanTity = Record.get('Quantity');
            if (QuanTity <= 0)
                QuanTity = 1;
            Record.set('Quantity', QuanTity);
            Record.set('VATPercent', 0);
            Record.set('DiscountPercent', 0);     
            Record.set('WarehouseId', record.data.WarehouseId);
            CaculatorOtherField(Record);
        }
        function NewMasterProcess() {
            DirectMethod.NewDataProcess({
                success: function(resul) {
                    btnNew.setDisabled(true);
                    txtVoucherNo.focus(true, 10);
                }
            });
        }
        var clIndex;
        function CheckBeforSave(record) {
            
            var strMesseger = '', fn = '';
            if (txtVoucherNo.getValue() == '') {
                strMesseger += 'Mã phiếu không được trống';
                fn = 'txtVoucherNo.focus(true, 10);';
            }
            else if (dfDocumentDate.getValue() == '') {
                strMesseger += '<br/>Ngày nhập không được trống';
                fn = 'dfDocumentDate.focus(true, 10);';
            }
            if (record != null) {
                var index = grDetail.getStore().indexOf(grDetail.getStore().getById(LastSelectDetailID));
                if (record.data['ProductId']<=0) {
                    strMesseger += "Nhập mặt hàng trước khi lưu </BR>";
                    clIndex = grDetail.colModel.getIndexById('clProductName');
                    fn = 'StartEdit_Grid(grDetail, '+index+', ' + clIndex + ')';
                }
                else
                    if (record.data['Quantity'] <= 0) {
                    strMesseger += "Nhập số lượng trước khi lưu</BR>";
                    clIndex = grDetail.colModel.getIndexById('clProductName');
                    fn = 'StartEdit_Grid(grDetail, '+index+', ' + clIndex + ')';
                }
            } else {
                var records = grDetail.store.getModifiedRecords();
                if (records.length <= 0 && hdDocumentID.getValue() == '')
                    strMesseger += '<br/>nhập chi tiết phiếu trước khi lưu';
                for (var i = 0; i < records.length; i++) {
                    if (records[i].data.WarehouseId == '' || records[i].data.UnitId == '' || records[i].data.ProductId == '' || records[i].data.Quantity < 0) {
                        strMesseger += 'Dữ liệu chi tiết chưa hợp lệ vui lòng kiểm tra lại';
                        break;
                    }
                }
            }    
          
            if (strMesseger != '') {
                vnMessageBox('Thông báo !', strMesseger, Ext.MessageBox.OK, fn, Ext.MessageBox.INFO, 1);
                return false;
            }
            return true;
        }
        /*
        Tính lại thông tin cho một số 
        */
        function CaculatorOtherField(Records) {
            var Record = Records;
            if (Records == undefined || Records == null)
                Record = grDetail.selModel.selections.items[0];
            if (Record == undefined || Record == null)
                return;
            var UnitPrice = Record.get('UnitPrice');
            var QuanTity = Record.get('Quantity');
            var VATPercent = Record.get('VATPercent');
            var Amount = UnitPrice * QuanTity;
            Record.set('Amount', Amount);
            var VATAmount = VATPercent * Amount * 1.1;
            Record.set('VATAmount', VATAmount);
            var DiscountPercent = Record.get('DiscountPercent');
            var DiscountAmount = (VATAmount + Amount) * DiscountPercent * 1.1
            Record.set('DiscountAmount', DiscountAmount);
            var TotalAmount = (VATAmount + Amount) - DiscountAmount
            Record.set('TotalAmount', TotalAmount);
            Amount = 0, DiscountAmount = 0, VATAmount = 0, TotalAmount;
            var Quantity = 0;
            var items = grDetail.store.data.items;
            for (var i = 0; i < items.length; i++) {
                if (items[i].get('Amount') != null)
                    Amount += items[i].get('Amount');
                if (items[i].get('Quantity') != null)
                    Quantity += items[i].get('Quantity');
                if (items[i].get('DiscountAmount') != null)
                    DiscountAmount += items[i].get('DiscountAmount');
                if (items[i].get('VATAmount') != null)
                    VATAmount += items[i].get('VATAmount');
            }
            dpDiscountAmount.setValue(DiscountAmount);
            dpVATAmount.setValue(VATAmount);
            dpQuantity.setValue(Quantity);
            dpAmount.setValue(Amount);
            dpTotalAmount.setValue(TotalAmount);
        }
        function Currency_Change(combo,record,index) {           
            if (record.data.Rate > 0)
                nfRate.setValue(record.data.Rate);
            else nfRate.setValue(1);

        }
        function Object_Change(combo, record, index) {
            if (record.data.ObjectId > 0) {
                txtTaxCode.setValue(record.data.TaxCode);
                txtAddress.setValue(record.data.Address);
            }
        }
        function Unit_Select(cb, record, index) {
            var Record = grDetail.store.getById(LastSelectDetailID);
            if (Record != null) {
                Record.set('UnitId', record.data.RatioUnit);
                Record.set('UnitName', record.data.RatioName);
            }
        }
        
        function Unit_BeforeShow() {
            var Record = grDetail.store.getById(LastSelectDetailID);
            DirectMethod.UnitBindingData(Record.data.ProductId, {
                success: function() {
                    var test = 1;
                }
            })
        }
        function BeforeRowSelectDetail(SelectionModel, rowIndex, keepExisting, record) {
            CurrentRecord = record;
            if (LastSelectDetailID != 0 && LastSelectDetailID != record.id) {
                if (!btnSave_Click(false,"Complete_Search(grDetail);")) {
                    return false;
                }
            }
            LastSelectDetailID = record.id;
        }

        function btnSave_Click(isMaster,fn) {

            if (LastSelectDetailID != 0) {
                var Record = grDetail.store.getById(LastSelectDetailID);
                if (isMaster == true)
                    grDetail.stopEditing();
                if (Record!=undefined&&(Record.modified != null || isMaster) )
                {
                        SaveProcess(isMaster,Record,fn);
                            return false;                       
                }
            }
            return true;
        }
        /*
        Thuc hien lưu
        */
        function SaveProcess(isMaster, recode, fn) {
            if (recode != null && !isMaster)
            if (!CheckBeforSave(recode))
                return;
            var JsonDetail = ''
            if (recode != null && recode.modified != null)
                JsonDetail = '[' + Ext.encode(recode.data) + ']';
            DirectMethod.SaveProcess(isMaster, JsonDetail, {
                success: function(DetailID) {
                    if (isMaster) {
                        vnMessageBox('Thông báo !', 'Lưu thành công', Ext.MessageBox.OK, 'txtVoucherNo.focus(true, 10);', Ext.MessageBox.INFO, 1);
                    } else
                        if (DetailID > 0) {
                        btnNew.setDisabled(false);
                        grDetail.store.getById(LastSelectDetailID).commit();
                        grDetail.store.updateRecordId(LastSelectDetailID, DetailID);
                        LastSelectDetailID = DetailID;
                        if (fn != undefined && fn != null)
                            eval(fn);                       
                    } else vnMessageBox('Thông báo !', 'Lưu thành thất bại', Ext.MessageBox.OK, 'txtVoucherNo.focus(true, 10);', Ext.MessageBox.INFO, 1);
                }
            });
        }
        